package array

type Solution struct {
}

func (Solution) maxProduct(nums []int) int {
	min, max := make([]int, len(nums)), make([]int, len(nums))
	min[0], max[0] = nums[0], nums[0]
	result := max[0]
	for i := 1; i < len(nums); i++ {
		if nums[i] > 0 {
			max[i] = maxVal(max[i-1]*nums[i], nums[i])
			min[i] = minVal(min[i-1]*nums[i], nums[i])
		} else {
			max[i] = maxVal(min[i-1]*nums[i], nums[i])
			min[i] = minVal(max[i-1]*nums[i], nums[i])
		}
		if max[i] > result {
			result = max[i]
		}
	}
	return result
}

func maxProduct(nums []int) int {
	min, max := nums[0], nums[0]
	result := max
	for i := 1; i < len(nums); i++ {
		if nums[i] > 0 {
			max = maxVal(max*nums[i], nums[i])
			min = minVal(min*nums[i], nums[i])
		} else {
			lastMax := max //非常重要
			max = maxVal(min*nums[i], nums[i])
			min = minVal(lastMax*nums[i], nums[i])
		}
		if max > result {
			result = max
		}
	}
	return result
}

func maxVal(left, right int) int {
	if left < right {
		return right
	}
	return left
}
func minVal(left, right int) int {
	if left < right {
		return left
	}
	return right
}
